package com.itruth.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.itruth.dao.UserDao;
import com.itruth.entity.User;
import com.itruth.util.ConnUtil;

public class UserDaoImpl implements UserDao {
	
	@Override
	public boolean accountIsExist(String userName) throws SQLException {
		int count = 0;
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = ConnUtil.getConn();
			ps = conn
					.prepareStatement("select count(1) from user where username = ?");

			ps.setString(1, userName);
			ResultSet rs = ps.executeQuery();
			
			if (rs.next()) {
				count = rs.getInt(1);
			}
			
		} finally {
			try {
				if (null != ps) {
					ps.close();
					ps = null;
				}
				if (null != conn) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return count > 0;
		
	}
		
	@Override
	public void insert(User user) throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = ConnUtil.getConn();
			ps = conn.prepareStatement("insert into user(username, password) values (?, ?)");
			
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getPassword());
			ps.executeUpdate();
			
		} catch (SQLException e) {
			throw e;
		} finally {

			try {
				if (null != ps) {
					ps.close();
					ps = null;
				}
				if (null != conn) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
